import asyncio
import sys
import os

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

from src.core.context_orchestrator import ContextOrchestrator
from src.config import load_config
from loguru import logger

async def debug_neo4j_concepts():
    """调试 Neo4j 概念数据"""
    
    # 加载配置
    config = load_config()
    
    # 初始化上下文编排器
    context_orchestrator = ContextOrchestrator(config)
    await context_orchestrator.initialize()
    
    try:
        neo4j_client = context_orchestrator.db_manager.neo4j_client
        
        print("🔍 调试 Neo4j 概念数据...")
        
        # 1. 查看概念节点的实际属性
        print("\n📋 查看概念节点的实际属性:")
        query = """
        MATCH (c:Concept)
        RETURN keys(c) as properties, c
        LIMIT 5
        """
        result = await neo4j_client.execute_query(query)
        for record in result:
            print(f"  属性: {record['properties']}")
            print(f"  节点: {dict(record['c'])}")
            print()
        
        # 2. 查找包含 'python' 的概念（不区分大小写）
        print("\n🔍 查找包含 'python' 的概念:")
        query = """
        MATCH (c:Concept)
        WHERE toLower(c.name) CONTAINS toLower('python')
        RETURN c.concept_id, c.name
        LIMIT 10
        """
        result = await neo4j_client.execute_query(query)
        print(f"找到 {len(result)} 个包含 'python' 的概念:")
        for record in result:
            print(f"  - ID: {record['c.concept_id']}, Name: {record['c.name']}")
        
        # 3. 查找包含 '游戏' 的概念
        print("\n🎮 查找包含 '游戏' 的概念:")
        query = """
        MATCH (c:Concept)
        WHERE toLower(c.name) CONTAINS toLower('游戏')
        RETURN c.concept_id, c.name
        LIMIT 10
        """
        result = await neo4j_client.execute_query(query)
        print(f"找到 {len(result)} 个包含 '游戏' 的概念:")
        for record in result:
            print(f"  - ID: {record['c.concept_id']}, Name: {record['c.name']}")
        
        # 4. 测试 find_concepts_by_name 方法
        print("\n🔧 测试 find_concepts_by_name 方法:")
        concepts = await neo4j_client.find_concepts_by_name('python', limit=5)
        print(f"find_concepts_by_name('python') 返回 {len(concepts)} 个结果:")
        for concept in concepts:
            print(f"  - {concept}")
        
        # 5. 测试查找相关概念
        if concepts:
            concept_id = concepts[0]['concept_id']
            print(f"\n🔗 测试查找概念 {concept_id} 的相关概念:")
            related = await neo4j_client.find_related_concepts(concept_id, depth=1, limit=5)
            print(f"find_related_concepts('{concept_id}') 返回 {len(related)} 个结果:")
            for rel in related:
                print(f"  - {rel}")
        
    except Exception as e:
        logger.error(f"调试过程中出错: {e}")
        import traceback
        traceback.print_exc()
    
    finally:
        # 关闭连接
        await context_orchestrator.shutdown()
        print("🔒 数据库连接已关闭")

if __name__ == "__main__":
    asyncio.run(debug_neo4j_concepts())